<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use Illuminate\Http\Request;
use App\Http\Response\ResponseEnum;
use Illuminate\Support\Facades\Hash;
use App\Services\JwtService;
use App\Exceptions\BusinessException;

class AdminController extends BaseController
{
    public function register(Request $request)
    {
        try {
            $request->validate([
                'username' => 'required|max:32',
                'password' => 'required',
                'confirm_password' => 'required',
            ]);

            $post = $request->post();

            if ($post['confirm_password'] != $post['password']) {
                return $this->fail(ResponseEnum::USER_SERVICE_REGISTER_ERROR, null);
            }

            if (Admin::query()->where('username', $post['username'])->exists()) {
                return $this->fail(ResponseEnum::USER_ACCOUNT_REGISTERED, null);
            }

            $hash_password = Hash::make($post['password']);

            $admin = new Admin();
            $admin->username = $post['username'];
            $admin->password = $hash_password;
            $admin->avatar = '';
            $admin->save();

            $jwt = new JwtService;

            $token = $jwt->encode($admin->id);

            $data = [
                'user_id' => $admin->id,
                'username' => $admin->username,
                'token' => $token,
            ];
        } catch (\Exception $exception) {
            throw new BusinessException(ResponseEnum::USER_SERVICE_REGISTER_ERROR, $exception->getMessage());
        }


        return $this->success($data);
    }

    public function login(Request $request)
    {
        try {
            $request->validate([
                'username' => 'required|max:32',
                'password' => 'required',
            ]);

            $post = $request->post();

            $admin = Admin::query()->where('username', $post['username'])->first();

            if (is_null($admin)) {
                return $this->fail(ResponseEnum::USER_SERVICE_LOGIN_ERROR, null, '用户不存在');
            }

            if (!hash::check($post['password'], $admin->password)) {
                return $this->fail(ResponseEnum::USER_SERVICE_LOGIN_ERROR, null, '密码错误');
            }

            $jwt = new JwtService;

            $token = $jwt->encode($admin->id);

            $data = [
                'user_id' => $admin->id,
                'username' => $admin->username,
                'token' => $token,
            ];
        } catch (\Exception $exception) {
            throw new BusinessException(ResponseEnum::USER_SERVICE_LOGIN_ERROR, $exception->getMessage());
        }

        return $this->success($data);
    }

    public function logout(Request $request)
    {
        if ($request->attributes->has('admin_info')) {
            $request->attributes->remove('admin_info');
        }

        return $this->success();
    }

}